<!--
  ~ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
  ~ Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
  ~ Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~ http://opensource.org/licenses/MIT
  ~ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  ~ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations under the License.
  ~
  -->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="/console/static/favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="/console/static/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="/console/static/bk-magic/bk-magic-vue.min.css">
    <!-- <link rel="preload" href="http://imgcache.qq.com/ptlogin/ac/v9/js/ptloginout.js" as="script" /> -->
    <link rel='preload' as='script' href="/console/static/vue.min.js" />
    <link rel='preload' as='script' href="/console/static/vuex.min.js" />
    <link rel='preload' as='script' href="/console/static/vue-router.min.js" />
    <link rel='preload' as='script' href="/console/static/bk-magic/bk-magic-vue.min.js" />
    <!-- devops:css -->
    <% for (key in htmlWebpackPlugin.files.css) { %>
    <link href="<%= htmlWebpackPlugin.files.css[key] %>" rel="stylesheet" />
    <% } %>
    <!-- end devops:css -->
    <title>蓝鲸容器管理平台|蓝鲸智云</title>
</head>

<body>
    <div id="devops-root">
        <div class="bk-loading" style="position: absolute;">
            <div class="bk-loading-wrapper">
                <div class="bk-loading1">
                    <div class="point point1"></div>
                    <div class="point point2"></div>
                    <div class="point point3"></div>
                    <div class="point point4"></div>
                </div>
                <div class="bk-loading-title"></div>
            </div>
        </div>
    </div>
    <script src="/console/static/vue.min.js"></script>
    <script src="/console/static/vuex.min.js"></script>
    <script src="/console/static/vue-router.min.js"></script>
    <script src="/console/static/bk-magic/bk-magic-vue.min.js"></script>
    <!-- <script defer src="http://imgcache.qq.com/ptlogin/ac/v9/js/ptloginout.js"></script> -->
    <script src="/console/static/env.js"></script>
    <script src="/console/static/service.js"></script>
    <!-- devops:assets -->
    <!-- end devops:assets -->

    <script>
        // 动态加载js
        function importScript(src, oHead, fOnload) {
            var oScript = document.createElement('script')
            oScript.type = 'text\/javascript'

            if (fOnload) {
                oScript.onload = fOnload
            }

            oScript.setAttribute('src', src)
            oScript.setAttribute('defer', '')
            oHead.appendChild(oScript)
        }

        // 动态加载css
        function importStyle(href, oHead) {
            var oStyle = document.createElement('link')
            oStyle.setAttribute('rel', 'stylesheet')
            oStyle.setAttribute('type', 'text/css')
            oStyle.setAttribute('href', href)
            oHead.appendChild(oStyle)
        }

        for (var i = 0; i < window.jsAssets.length; i++) {
            var js = window.jsAssets[i]
            if (js.indexOf('vendors') > -1) {
                importScript(js, document.body)
            }
        }
    </script>
    <script>
        //  获取所有服务列表

        function asyncGet(url) {
            return new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest()
                xhr.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        resolve(JSON.parse(xhr.responseText).data)
                    } else if (this.status == 401) {
                        window.location.href = LOGIN_SERVICE_URL + '/?c_url=' + window.location.href
                    } else if (this.readyState == 4 && this.status > 400) {
                        reject({
                            status: this.status,
                            message: this.status === 503 ? '服务维护中，请稍候...' : '服务器内部异常'
                        })
                    }
                }
                xhr.withCredentials = true
                xhr.open('GET', url)
                xhr.send()
            })
        }

        function fetchAllServices() {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/services/')
        }

        function fetchAllProjects() {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/projects/')
        }

        function requestUser() {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/users')
        }


        function getServiceObject(serviceList) {
            var serviceMap = {}
            var iframeRoutes = []
            for (var i = 0; i < serviceList.length; i++) {
                var children = serviceList[i].children
                for (var j = 0; j < children.length; j++) {
                    var mod = children[j].link_new.replace(/^\/?(\w+)\S*/, '$1')
                    var serviceTitle = children[j].name.replace(/\(\S+?\)/, '')
                    serviceMap[mod] = children[j]
                    if (children[j].inject_type === 'iframe') {
                        iframeRoutes.push({
                            path: mod + (children[j].show_project_list ? '/:projectId?' : ''),
                            name: mod,
                            meta: {
                                showProjectList: children[j].show_project_list,
                                showNav: children[j].show_nav,
                                projectIdType: children[j].project_id_type,
                                header: serviceTitle,
                                logo: mod
                            }
                        })
                    }
                }
            }
            return {
                serviceMap: serviceMap,
                iframeRoutes: iframeRoutes
            }
        }

        Promise.all([
            fetchAllProjects(),
            // fetchAllServices(),
            requestUser()
        ]).then(function (response) {
            var projectList = response[0]
            var allServices = services
            var userInfo = response[1]
            var path = location.pathname.replace('/console', '')
            var headTag = document.head || document.getElementsByTagName('head')[0]
            var pathReg = /^\/(\w+)\/?/
            var serviceObject = getServiceObject(allServices)
            var serviceMap = serviceObject.serviceMap
            var serviceMatchResult = path.match(pathReg)
            var subServiceId = serviceMatchResult ? serviceMatchResult[1] : null
            var page = serviceMap[subServiceId] || null

            window.allServices = allServices
            window.serviceObject = serviceObject
            window.currentPage = page
            window.projectList = projectList

            userInfo.isAuthenticated = true
            window.userInfo = userInfo

            if (page && page.inject_type === 'amd') {
                var inject_type = page.inject_type
                var js_url = page.js_url
                var css_url = page.css_url
                var title = page.title

                importScript(js_url, document.body, loadJsAssets)
                importStyle(css_url, headTag)
            } else {
                loadJsAssets()
            }
        }).catch(function (e) {
            console.log(e)
            printError(e.status, e.message)
        })


        function printError(status, msg) {
            document.writeln(
                '<div style="height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column;">' +
                '<img src="/console/static/' + status + '.png" />' +
                '<p style="font-size: 20px; color: #979797; margin: 32px 0;">' + msg + '</p>' +
                '</div>'
            )
        }

        function loadJsAssets() {
            for (var i = 0; i < window.jsAssets.length; i++) {
                var js = window.jsAssets[i]
                if (js.indexOf('vendors') === -1) {
                    importScript(js, document.body)
                }
            }
        }

        // 接入mta统计
        var _mtac = {};
        (function () {
            var mta = document.createElement("script");
            mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
            mta.setAttribute("name", "MTAH5");
            mta.setAttribute("sid", "500630653");

            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(mta, s);
        })();
    </script>
</body>

</html>